package edu.ccut.saturn.studio.wfg.model;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.gef.ui.parts.GraphicalEditorWithFlyoutPalette;
import org.w3c.dom.Document;

import edu.ccut.saturn.studio.logic.model.BasicShape;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnEndNode;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnInformationNode;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnStartNode;

public class ShapesDiagram extends BasicShape {

	private static final String SHAPE_DIAGRAME_NULL = "";

	private static final long serialVersionUID = 238078924439643564L;
	
	public static final String CHILD_ADDED_PROP = "ShapesDiagram.ChildAdded";

	public static final String CHILD_REMOVED_PROP = "ShapesDiagram.ChildRemoved";
	
	private List<Shape> shapes = new ArrayList<Shape>();
	
	private GraphicalEditorWithFlyoutPalette editor;
	
	private Document doc;
	
	public ShapesDiagram() {
		super();
	}

	public ShapesDiagram(GraphicalEditorWithFlyoutPalette editor,Document doc) {
		super();
		this.editor = editor;
		this.doc = doc;
	}
	
	public boolean addShape(Shape shape) {
		if (shapes != null) {
			// 只能有一个开始节点，一个信息节点，一个结束节点
			if (shape instanceof SaturnStartNode) {
				for (int i = 0; i < shapes.size(); i++) {
					if ((shapes.get(i) instanceof SaturnStartNode)) {
						return false;
					}
				}
			} else if (shape instanceof SaturnInformationNode) {
				for (int i = 0; i < shapes.size(); i++) {
					if ((shapes.get(i) instanceof SaturnInformationNode)) {
						return false;
					}
				}
			} else if (shape instanceof SaturnEndNode){
				for (int i = 0; i < shapes.size(); i++){
					if ((shapes.get(i) instanceof SaturnEndNode)){
						return false;
					}
				}
			}
			
			shape.setParent(this);
			shapes.add(shape);
			firePropertyChange(CHILD_ADDED_PROP, null, shape);
			return true;
		}
		
		return false;
	}

	public void addShapes(List<Shape> shapes) {
		if (shapes != null) {

			for (Shape shape : shapes) {
				this.addShape(shape);
			}
		}
	}

	public List<Shape> getShapes() {
		return shapes;
	}

	public boolean removeShape(Shape s) {
		if (s != null && shapes.remove(s)) {
			firePropertyChange(CHILD_REMOVED_PROP, null, s);
			return true;
		}
		return false;
	}

	public String getNextValidShapeId() {
		int maxId = 0;

		for (Shape shape : shapes) {
			try {
				int shapeId = Integer.parseInt(shape.getId());

				if (maxId < shapeId) {
					maxId = shapeId;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		return ++maxId + SHAPE_DIAGRAME_NULL;
	}

	// 后加的
	public GraphicalEditorWithFlyoutPalette getEditor() {
		return editor;
	}
	
	public void setEditor(GraphicalEditorWithFlyoutPalette editor) {
		this.editor = editor;
	}
}